/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lanren.easyhttp.func;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lanren.easyhttp.model.ApiResult;
import com.lanren.easyhttp.utils.HttpLog;
import com.lanren.easyhttp.utils.Utils;

import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import okhttp3.ResponseBody;


/**
 * <p>描述：定义了ApiResult结果转换Func</p>
 * 作者： zhouyou<br>
 * 日期： 2017/3/15 16:52 <br>
 * 版本： v1.0<br>
 */
@SuppressWarnings("unchecked")
public class ApiResultFunc<T> implements Function<ResponseBody, ApiResult<T>> {
    protected Type type;
    protected Gson gson;

    public ApiResultFunc(Type type) {
        gson = new GsonBuilder()
                .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)//忽略修饰类型
                .serializeNulls()//智能null
                .create();
        this.type = type;
    }

    @Override
    public ApiResult<T> apply(@NonNull ResponseBody responseBody) throws Exception {
        HttpLog.i("+++ApiResultFunc+++" + Thread.currentThread().getName());
        ApiResult<T> apiResult = new ApiResult<>();
        apiResult.setCode(-1);
        HttpLog.i("+++ApiResultFunc 自定义ApiResult+++" + Thread.currentThread().getName());
        final Class<T> cls = (Class) ((ParameterizedType) type).getRawType();
        if (ApiResult.class.isAssignableFrom(cls)) {
            final Type[] params = ((ParameterizedType) type).getActualTypeArguments();
            final Class clazz = Utils.getClass(params[0], 0);
            final Class rawType = Utils.getClass(type, 0);
            try {
                String json = responseBody.string();
                //增加是List<String>判断错误的问题
                if (!List.class.isAssignableFrom(rawType) && clazz.equals(String.class)) {
                    ApiResult result = gson.fromJson(json, type);
                    if (result != null) {
                        apiResult = result;
                        apiResult.setData((T) result.getMsg());
                    } else {
                        apiResult.setMsg("json is null");
                    }
                } else {
                    ApiResult result = gson.fromJson(json, type);
                    if (result != null) {
                        apiResult = result;
                    } else {
                        apiResult.setMsg("json is null");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                apiResult.setMsg(e.getMessage());
            } finally {
                responseBody.close();
            }
        } else {
            apiResult.setMsg("ApiResult.class.isAssignableFrom(cls) err!!");
        }

        return apiResult;
    }
}
